package com.item.Handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.item.pojo.User;
import com.item.service.userservice;
import com.item.utils.JwtUtil;
import com.item.utils.RedisUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@Component
@AllArgsConstructor
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {


    private userservice userservice;
    private ObjectMapper objectMapper;
private RedisUtil redisUtil;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        HashMap<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "登录成功");

        Map<String, Object> claims=new HashMap<>();

      //获取aut对象
        String username = authentication.getName();
        User user= userservice.getusername(username);
        //发送token
        claims.put("id",user.getId());
        claims.put("username",user.getUsername());
        String token= JwtUtil.genToken(claims);
        System.out.println(token);
        result.put("token",token);

        Object authToken= redisUtil.hashSet("token",authentication.getName(),authentication,60*60*24*7);
        System.out.println(authToken);
        System.out.println("==============");
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
}
//目前问题是在sucesshandler响应的数据前端vue拿不到，且securityfitter无法强制转换httpservlet，